import moment from "moment";
import { pageConst, districtMap, SH_STAGE_MAP } from "./PageConst";
import {
  CANTON_COUNT_TAG,
  provinceMap,
  hbCityMap,
  ycDistrictMap,
} from "./const";

export default {
  defaults(props) {
    return {
      wHeight: "100vh",
      mHeight: 920 / 3,
      aHeight: 250,
      ...pageConst,
    };
  },

  async init(ctx, props) {
    getFgStageCount(ctx, props);
    // 劳务实名制人员数量
    getLaborCount(ctx);
    getFgLaborCount(ctx);
    // 复工人员数量
    getFgCount(ctx);
    // 检测&商品砼
    getFgJcSptCioCount(ctx);
    // 打卡（上报体温）
    // getFgClockCount(ctx);
    // 复工工程今日新增
    getXzxmCount(ctx, { shzt: "办理完毕" }, (count) => {
      ctx.setState(
        React.addons.update(ctx.getState(), {
          fggcXzCount: { $set: count },
        })
      );
    });
    // 在建工程今日新增
    getXzxmCount(ctx, {}, (count) => {
      ctx.setState(
        React.addons.update(ctx.getState(), {
          zjgcXzCount: { $set: count },
        })
      );
    });
  },

  // 下面的数据
  async showBottomCount(ctx, props) {
    const { bottomContentTag } = props;
    ctx.setState(
      React.addons.update(ctx.getState(), {
        bottomContentTag: { $set: bottomContentTag },
      })
    );
    if (bottomContentTag === "CFD") {
      // 获取人员出发地数据（全国、湖北和宜昌）
      queryCfdMddCount(ctx, { tag: "A" });
      queryCfdMddCount(ctx, { tag: "B" });
      queryCfdMddCount(ctx, { tag: "C" });
    } else if (bottomContentTag === "MDD") {
      // 获取人员目的地数据
      queryCfdMddCount(ctx, { tag: "D" });
    } else if (bottomContentTag === "XMZB") {
      // 获取项目复工数据
      getFgStageCount(ctx, { visible: false });
    }
  },

  // 复工机构弹框
  async showFgjgDialog(ctx, props) {
    const { visible, title, key, dwlb } = props;
    ctx.setState(
      React.addons.update(ctx.getState(), {
        fgjgDialog: {
          visible: { $set: visible },
          title: { $set: title },
          type: { $set: key },
        },
      })
    );
    initFgjgData(ctx, { dwlb });
    fgStageCioPage(ctx, { dwlb });
  },

  // 图片弹框
  async showPhotoDialog(ctx, props) {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        photoDialog: {
          visible: { $set: props.visible },
          photoUrl: { $set: props.url },
          whRate: { $set: props.whRate },
        },
      })
    );
  },

  async realNamePageChange(ctx, props) {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        realNameDialog: {
          dataLoading: { $set: true },
        },
      })
    );
    const { key, currentPage = 1, pageSize = 10 } = props;
    let jsxdata = {
      data: [],
      currentPage: 1,
      totalCount: 0,
    };
    let selectType = null;
    if (key === "SMZS") {
      selectType = 1;
    } else if (key === "SMXZ") {
      selectType = 2;
    } else if (key === "TWYC") {
      selectType = 4;
    }
    const callback = (response) => {
      if (response) {
        const { current, total, records } = response;
        jsxdata = {
          data: records,
          currentPage: current,
          totalCount: total,
        };
        if (key === "SMZS") {
          ctx.setState(
            React.addons.update(ctx.getState(), {
              realCount: { $set: total },
            })
          );
        } else if (key === "SMXZ") {
          ctx.setState(
            React.addons.update(ctx.getState(), {
              addRealCount: { $set: total },
            })
          );
        } else if (key === "TWYC") {
          ctx.setState(
            React.addons.update(ctx.getState(), {
              clockCount: { $set: total },
            })
          );
        }
      }
      ctx.setState(
        React.addons.update(ctx.getState(), {
          realNameDialog: {
            jsxdata: { $set: jsxdata },
            dataLoading: { $set: false },
          },
        })
      );
    };
    laborPersonPage(
      ctx,
      { selectType, limit: pageSize, page: currentPage },
      callback
    );
  },

  // 实名认证人员弹框
  async showRealNameDialog(ctx, props) {
    const { key, title, visible } = props;
    ctx.setState(
      React.addons.update(ctx.getState(), {
        realNameDialog: {
          visible: { $set: visible },
          key: { $set: key },
          title: { $set: title },
          dataLoading: { $set: true },
        },
      })
    );
    let jsxdata = {
      data: [],
      currentPage: 1,
      totalCount: 0,
    };
    let selectType = null;
    if (key === "SMZS") {
      selectType = 1;
    } else if (key === "SMXZ") {
      selectType = 2;
    } else if (key === "TWYC") {
      selectType = 4;
    }
    const callback = (response) => {
      if (response) {
        const { current, total, records } = response;
        jsxdata = {
          data: records,
          currentPage: current,
          totalCount: total,
        };
        if (key === "SMZS") {
          ctx.setState(
            React.addons.update(ctx.getState(), {
              realCount: { $set: total },
            })
          );
        } else if (key === "SMXZ") {
          ctx.setState(
            React.addons.update(ctx.getState(), {
              addRealCount: { $set: total },
            })
          );
        } else if (key === "TWYC") {
          ctx.setState(
            React.addons.update(ctx.getState(), {
              clockCount: { $set: total },
            })
          );
        }
      }
      ctx.setState(
        React.addons.update(ctx.getState(), {
          realNameDialog: {
            jsxdata: { $set: jsxdata },
            dataLoading: { $set: false },
          },
        })
      );
    };
    laborPersonPage(ctx, { selectType, limit: 10, page: 1 }, callback);
  },

  // 新增项目弹框
  async showXzxmDialog(ctx, props) {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        xzxmDialog: {
          visible: { $set: props.visible },
          shzt: { $set: props.shzt },
          title: { $set: props.title },
        },
      })
    );
    getXzFgEng(ctx, props, (resposne) => {
      const { total, pageSize, current, data } = resposne;
      ctx.setState(
        React.addons.update(ctx.getState(), {
          xzxmDialog: {
            jsxdata: {
              data: { $set: data },
              currentPage: { $set: current },
              totalCount: { $set: total },
            },
            pageSize: { $set: pageSize },
          },
        })
      );
    });
  },

  // 新增项目分页查询
  async xzxmPageChange(ctx, props) {
    getXzFgEng(ctx, props, (response) => {
      const { total, pageSize, current, data } = response;
      ctx.setState(
        React.addons.update(ctx.getState(), {
          xzxmDialog: {
            jsxdata: {
              data: { $set: data },
              currentPage: { $set: current },
              totalCount: { $set: total },
            },
            pageSize: { $set: pageSize },
          },
        })
      );
    });
  },

  // 复工项目详情弹框
  async showDialog(ctx, props) {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        dVisible: { $set: props.visible },
        dTitle: { $set: props.title },
      })
    );
    getFgStageCount(ctx, props);
    getFgEngPage(ctx, props);
  },

  async pageChange(ctx, props) {
    getFgEngPage(ctx, props);
  },

  async fgjgPageChange(ctx, props) {
    fgStageCioPage(ctx, props);
  },
};

function setDialogTopValues(ctx, props = {}) {
  const { visible } = props;
  if (visible) {
    const { title, stageCount } = props;
    const count = (prv, next) => prv + next.sl;
    const data = stageCount.filter((item) =>
      title === "全市" ? true : item.cantonname === districtMap[title]
    );
    const zjgcCount = data.reduce(count, 0);
    const blwbCount = data
      .filter((item) => item.shzt === "办理完毕")
      .reduce(count, 0);
    const tbz = data.filter((item) => item.shzt === "填报中").reduce(count, 0);
    const jsdwTh = data
      .filter((item) => item.shzt === "建设单位退回")
      .reduce(count, 0);
    const jsdwQr = data
      .filter((item) => item.shzt === "待建设单位确认")
      .reduce(count, 0);
    const jldwTh = data
      .filter((item) => item.shzt === "监理单位退回")
      .reduce(count, 0);
    const jldwQr = data
      .filter((item) => item.shzt === "待监理确认")
      .reduce(count, 0);
    const zgbmTh = data
      .filter((item) => item.shzt === "主管部门退回")
      .reduce(count, 0);
    const zgbmQr = data
      .filter((item) => item.shzt === "待主管部门确认")
      .reduce(count, 0);

    ctx.setState(
      React.addons.update(ctx.getState(), {
        dialogData: {
          // 在建工程
          zjgcCount: { $set: zjgcCount },
          // 办理完毕
          blwbCount: { $set: blwbCount },
          // 复工率
          fgl: {
            $set:
              zjgcCount === 0
                ? 0
                : parseFloat(((blwbCount / zjgcCount) * 100).toFixed(2)),
          },
          // 施工单位
          sgdw: {
            tbz: { $set: tbz }, // 填报中
          },
          // 监理单位
          jldw: {
            th: { $set: jldwTh }, // 退回
            dqr: { $set: jldwQr }, // 待确认
          },
          // 建设单位
          jsdw: {
            th: { $set: jsdwTh }, // 退回
            dqr: { $set: jsdwQr }, // 待确认
          },
          // 主管部门
          zgbm: {
            th: { $set: zgbmTh }, // 退回
            dqr: { $set: zgbmQr }, // 待确认
          },
        },
      })
    );
  } else {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        dialogData: { $set: pageConst.dialogData },
      })
    );
  }
}

function setDialogTableValues(ctx, props) {
  const { total, pageSize, current, data } = props.response;
  ctx.setState(
    React.addons.update(ctx.getState(), {
      dShzt: { $set: props.shzt },
      dialogData: {
        jsxdata: {
          data: { $set: data },
          currentPage: { $set: current },
          totalCount: { $set: total },
        },
        pageSize: { $set: pageSize },
      },
    })
  );
}

function setStageCountValues(ctx, props) {
  const stageCount = props;
  const shzt510 = stageCount.filter((item) => item.shzt === "办理完毕");
  const res = [];
  Object.keys(districtMap).forEach((item) => {
    const data = shzt510.filter(
      (item2) => item2.cantonname === districtMap[item]
    );
    const totalData = stageCount.filter(
      (item2) => item2.cantonname === districtMap[item]
    );
    const fgsl = data.length === 0 ? 0 : data[0].sl;
    const total =
      totalData.length === 0
        ? 0
        : totalData.reduce((pre, next) => pre + parseInt(next.sl, 0), 0);
    res.push({
      name: item,
      value: total === 0 ? 0 : parseFloat(((fgsl / total) * 100).toFixed(2)),
      fgsl,
      total,
    });
  });

  const fgTotal = shzt510.reduce((pre, next) => pre + parseInt(next.sl, 0), 0);
  const total = stageCount.reduce((pre, next) => pre + parseInt(next.sl, 0), 0);
  const wfgTotal = stageCount
    .filter((item) => item.shzt !== "办理完毕")
    .reduce((pre, next) => pre + parseInt(next.sl, 0), 0);
  let color = "#FFF";
  if (fgTotal >= 0 && fgTotal < 20) {
    color = "#CDC9C9";
  } else if (fgTotal >= 20 && fgTotal < 40) {
    color = "#EE2C2C";
  } else if (fgTotal >= 40 && fgTotal < 60) {
    color = "#EE9A00";
  } else if (fgTotal >= 60 && fgTotal < 80) {
    color = "#436EEE";
  } else if (fgTotal >= 80) {
    color = "#00CD00";
  }

  ctx.setState(
    React.addons.update(ctx.getState(), {
      districtEngCountBar: {
        data: { $set: res },
      },
      districtEngCountPie: {
        data: {
          $set: [
            {
              name: "已复工",
              value: fgTotal,
              itemStyle: {
                normal: {
                  color,
                },
              },
            },
            {
              name: "未复工",
              value: wfgTotal,
              itemStyle: {
                normal: {
                  color: "#FFF",
                },
              },
            },
          ],
        },
        rate: {
          $set:
            total === 0 ? 0 : parseFloat(((fgTotal / total) * 100).toFixed(2)),
        },
      },
      fggcTotalCount: { $set: fgTotal },
      zjgcTotalCount: { $set: total },
    })
  );
}

// 复工项目及人员数量统计查询
export async function getFgCount(ctx) {
  const xmryCount = await ctx.fn.DB.fgfc.xmry
    .count({ Authorization: ctx.getState().token })
    .catch((error) => {
      console.log(error);
    });
  const {
    // gczs = 0, // 工程总数
    fggczs = 0, // 复工总数
    fgryzs = 0, // 复工人员总数
    // pgryzs = 0, // 派工人员总数
  } = xmryCount;
  ctx.setState(
    React.addons.update(ctx.getState(), {
      // fggcTotalCount: {$set: fggczs},
      fgryTotalCount: { $set: fgryzs },
    })
  );
}

// 查询县市区项目复工审核各阶段的数量
export async function getFgStageCount(ctx, props = {}) {
  ctx.fn.DB.fgfc.stage
    .count({ Authorization: ctx.getState().token })
    .then((response) => {
      if (response !== null) {
        setStageCountValues(ctx, response);
        setDialogTopValues(ctx, { ...props, stageCount: response });
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

// 复工工程分页查询
export async function getFgEngPage(ctx, props = {}) {
  const { visible } = props;
  if (visible) {
    const {
      currentPage = 1,
      pageSize = 10,
      title = "全市",
      shzt = null,
    } = props;
    let params = {
      current: currentPage,
      size: pageSize,
    };
    if (title !== "全市") {
      params.cantonname = districtMap[title];
    }
    if (shzt) {
      params.shzt = shzt;
    }
    ctx.fn.DB.fgfc.fg.eng
      .page({
        Authorization: ctx.getState().token,
        ...params,
      })
      .then((response) => {
        if (response !== null) {
          setDialogTableValues(ctx, { ...props, response });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }
}

export async function getLaborCount(ctx) {
  getLaborPersonTotalCount(ctx);
  getLaborPersonAdditionalCount(ctx);
  getLaborPersonSbtwCount(ctx);
}

// 劳务实名制人员数量统计查询
export async function getFgLaborCount(ctx) {
  const laborCount = await ctx.fn.DB.fgfc.labor
    .count({ Authorization: ctx.getState().token })
    .catch((error) => {
      console.log(error);
    });

  const {
    // realCount = 0, // 实名认证总数
    // addRealCount = 0, // 当日新增人数
    // mobileRealCount = 0, // 手机认证数量
    fillLocalCount = 0, // 已填写目的地数量
  } = laborCount;
  ctx.setState(
    React.addons.update(ctx.getState(), {
      // realCount: { $set: realCount },
      // addRealCount: { $set: addRealCount },
      // mobileRealCount: { $set: mobileRealCount },
      fillLocalCount: { $set: fillLocalCount },
    })
  );
}

// 复工检测商品砼企业数量统计查询
export async function getFgJcSptCioCount(ctx) {
  const response = await ctx.fn.DB.fgfc.jc.spt.cio
    .count({ Authorization: ctx.getState().token })
    .catch((error) => {
      console.log(error);
    });

  ctx.setState(
    React.addons.update(ctx.getState(), {
      fgJcCioCount: {
        $set: Array.isArray(response)
          ? response.filter((item) => item.dwlb === "检测机构").length
          : 0,
      },
      fgSptCioCount: {
        $set: Array.isArray(response)
          ? response.filter((item) => item.dwlb === "商品砼企业").length
          : 0,
      },
    })
  );
}

// 人员打卡数量统计查询
export async function getFgClockCount(ctx) {
  const today = moment().format("YYYY-MM-DD");
  const response = await ctx.fn.DB.fgfc.clock
    .count({ Authorization: ctx.getState().token, date: today })
    .catch((error) => {
      console.log(error);
    });

  ctx.setState(
    React.addons.update(ctx.getState(), {
      clockCount: {
        $set:
          Array.isArray(response) && response.length === 1
            ? response[0].count
            : 0,
      },
      clockDate: {
        $set:
          Array.isArray(response) && response.length === 1
            ? response[0].rq
            : "-",
      },
    })
  );
}

// 查询新增项目数量
export async function getXzxmCount(ctx, props, callback) {
  const beginTime = moment().format("YYYY-MM-DD");
  const endTime = moment().add(1, "days").format("YYYY-MM-DD");
  const response = ctx.fn.DB.fgfc.fg.eng
    .page({
      Authorization: ctx.getState().token,
      beginTime: beginTime,
      endTime: endTime,
      ...props,
    })
    .then((response) => {
      if (response) {
        if (callback) {
          callback(response.total || 0);
        }
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

// 查询新增项目
export async function getXzFgEng(ctx, props, callback) {
  const beginTime = moment().format("YYYY-MM-DD");
  const endTime = moment().add(1, "days").format("YYYY-MM-DD");
  const { currentPage = 1, pageSize = 10, shzt = null } = props;
  let params = {
    beginTime,
    endTime,
    current: currentPage,
    size: pageSize,
  };
  if (shzt) {
    params.shzt = shzt;
  }
  ctx.fn.DB.fgfc.fg.eng
    .page({
      Authorization: ctx.getState().token,
      beginTime: beginTime,
      endTime: endTime,
      ...params,
    })
    .then((response) => {
      if (response) {
        if (callback) {
          callback(response);
        }
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

export async function initFgjgData(ctx, props) {
  await ctx.fn.DB.fgfc.stage.cio
    .count({ Authorization: ctx.getState().token })
    .then((response) => {
      if (Array.isArray(response)) {
        const { dwlb } = props;
        const fgJcCioCount = response
          .filter(
            (item) => item.dwlb === "检测机构" && item.shzt === "办理完毕"
          )
          .reduce((prv, next) => prv + next.sl, 0);
        const fgSptCioCount = response
          .filter(
            (item) => item.dwlb === "商品砼企业" && item.shzt === "办理完毕"
          )
          .reduce((prv, next) => prv + next.sl, 0);
        const totalList = response.filter((item) => item.dwlb === dwlb);
        const totalCount = totalList.reduce((prv, next) => prv + next.sl, 0);
        const blwbCount = totalList
          .filter((item) => item.shzt === "办理完毕")
          .reduce((prv, next) => prv + next.sl, 0);
        const fgl =
          totalCount === 0 ? 0 : ((blwbCount / totalCount) * 100).toFixed(2);
        const tbzCount = totalList
          .filter((item) => item.shzt === "填报中")
          .reduce((prv, next) => prv + next.sl, 0);
        const dshCount = totalList
          .filter(
            (item) => item.shzt === "待审核" || item.shzt === "待重新审核"
          )
          .reduce((prv, next) => prv + next.sl, 0);
        const shthCount = totalList
          .filter((item) => item.shzt === "审核退回")
          .reduce((prv, next) => prv + next.sl, 0);
        ctx.setState(
          React.addons.update(ctx.getState(), {
            fgJcCioCount: { $set: fgJcCioCount },
            fgSptCioCount: { $set: fgSptCioCount },
            fgjgDialog: {
              totalCount: { $set: totalCount },
              blwbCount: { $set: blwbCount },
              fgl: { $set: fgl },
              tbzCount: { $set: tbzCount },
              dshCount: { $set: dshCount },
              shthCount: { $set: shthCount },
            },
          })
        );
      } else {
        ctx.setState(
          React.addons.update(ctx.getState(), {
            fgJcCioCount: { $set: 0 },
            fgSptCioCount: { $set: 0 },
            fgjgDialog: {
              totalCount: { $set: 0 },
              blwbCount: { $set: 0 },
              fgl: { $set: 0 },
              tbzCount: { $set: 0 },
              dshCount: { $set: 0 },
              shthCount: { $set: 0 },
            },
          })
        );
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

// 分页查询检测机构和商品砼已经审核通过可以开工的
export async function fgStageCioPage(ctx, props) {
  const { currentPage = 1, pageSize = 10, dwlb } = props;
  const params = {
    current: currentPage,
    pageSize,
  };
  if (dwlb) {
    params.dwlb = dwlb;
  }
  await ctx.fn.DB.fgfc.stage.cio
    .page({ Authorization: ctx.getState().token, ...params })
    .then((response) => {
      const { total = 0, pageSize = 10, current = 1, data = [] } = response;
      ctx.setState(
        React.addons.update(ctx.getState(), {
          fgjgDialog: {
            // 复工机构列表数据
            jsxdata: {
              data: { $set: data },
              currentPage: { $set: current },
              totalCount: { $set: total },
            },
            pageSize: { $set: pageSize },
          },
        })
      );
    })
    .catch((error) => {
      console.log(error);
    });
}

// 获取出发地数据（全国、湖北和宜昌）
export async function queryCfdMddCount(ctx, props) {
  const compare = (a, b) => b.count - a.count;
  await ctx.fn.DB.fgfc.canton
    .count({
      Authorization: ctx.getState().token,
      tag: CANTON_COUNT_TAG[props.tag],
    })
    .then((cantonCount) => {
      if (props.tag === "A") {
        ctx.setState(
          React.addons.update(ctx.getState(), {
            rycfd: {
              cn: {
                $set: cantonCount.sort(compare).map((item) => ({
                  ...item,
                  name: provinceMap[item.cantonName],
                })),
              },
            },
          })
        );
      }

      if (props.tag === "B") {
        ctx.setState(
          React.addons.update(ctx.getState(), {
            rycfd: {
              hb: {
                $set: cantonCount.sort(compare).map((item) => ({
                  ...item,
                  name: hbCityMap[item.cantonName],
                })),
              },
            },
          })
        );
      }
      if (props.tag === "C") {
        ctx.setState(
          React.addons.update(ctx.getState(), {
            rycfd: {
              yc: {
                $set: cantonCount.sort(compare).map((item) => ({
                  ...item,
                  name: ycDistrictMap[item.cantonName],
                })),
              },
            },
          })
        );
      }

      if (props.tag === "D") {
        ctx.setState(
          React.addons.update(ctx.getState(), {
            rymdd: {
              yc: {
                $set: cantonCount.sort(compare).map((item) => ({
                  ...item,
                  name: ycDistrictMap[item.cantonName],
                })),
              },
            },
          })
        );
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

// 实名认证总人数
export function getLaborPersonTotalCount(ctx) {
  const props = { selectType: 1 };
  laborPersonPage(ctx, props, (response) => {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        realCount: { $set: response ? response.total : 0 },
      })
    );
  });
}

// 今日新增实名人数
export function getLaborPersonAdditionalCount(ctx) {
  const props = { selectType: 2 };
  laborPersonPage(ctx, props, (response) => {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        addRealCount: { $set: response ? response.total : 0 },
      })
    );
  });
}

// 今日上报体温人数
export function getLaborPersonSbtwCount(ctx) {
  const props = { selectType: 4 };
  laborPersonPage(ctx, props, (response) => {
    ctx.setState(
      React.addons.update(ctx.getState(), {
        clockCount: { $set: response ? response.total : 0 },
      })
    );
  });
}

export async function laborPersonPage(ctx, props, callback) {
  const { selectType, limit = 10, page = 1 } = props;
  await ctx.fn.DB.fgfc.labor.person
    .page({
      Authorization: ctx.getState().token,
      selectType,
      limit,
      page,
    })
    .then((response) => {
      if (callback) {
        callback(response);
      }
    })
    .catch((error) => {
      console.log(error);
    });
}
